// sw.js

const CACHE_NAME = "v5";
const CACHE_URLS = ["/", "/style.css", "/icon.png"];

// 安装阶段：缓存资源
self.addEventListener("install", (event) => {
  console.log("[SW] 安装中...");
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      console.log("[SW] 缓存资源");
      return cache.addAll(CACHE_URLS);
    })
  );
  self.skipWaiting();
});

// 激活阶段：可清理旧缓存
self.addEventListener("activate", (event) => {
  console.log("[SW] 激活");
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys.map((key) => {
          if (key !== CACHE_NAME) {
            console.log("[SW] 删除旧缓存:", key);
            return caches.delete(key);
          }
        })
      )
    )
  );
  self.clients.claim();
});

// 拦截 fetch 请求，优先返回缓存
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((resp) => resp || fetch(event.request))
  );
});

// 接收 push 消息
self.addEventListener("push", (event) => {
  console.log("[SW] 收到 push 消息:", event.data?.text());
  const data = event.data?.json() || { title: "通知", body: "你有一条消息" };

  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: "/icon.png",
    })
  );
});
